I'm trying to figure out why this code does not compile?
I've created user defined destructor, so the move ctor and move assignment operator should not be created. So why complication fails, saying that my class does not fulfill the requirements?
#include <iostream>
#include <concepts>
#include <type_traits>
template<class T> requires (!std::movable<T>)
struct Singleton
{
};
struct Widget
{
~Widget() = default;
};
int main()
{
auto x = Singleton<Widget>{};
}
Edit. The same goes for this version.
#include <iostream>
#include <concepts>
#include <type_traits>
extern void fun();
template<class T> requires (!std::movable<T>)
struct Singleton
{
};
struct Widget
{
~Widget()
{
fun();
}
};
int main()
{
auto x = Singleton<Widget>{};
}
Error message
:23:28: note: constraints not satisfied
: In substitution of 'template requires !(movable) > struct Singleton [with T = Widget]':
:23:28: required from here
:8:8: required by the constraints of 'template requires !(movable) struct Singleton'
:7:30: note: the expression '!(movable) [with T = Widget]' evaluated to 'false'
7 | template requires (!std::movable)
Compiled used gcc (trunk) on godbolt. The only compilation flag I've used is -std=c++20
https://godbolt.org/z/sb535b1qv
There is no move constructor in either example. But that's not what std::movable checks. It defers the check you are intesteded in to std::move_constructible. That concept merely checks that an object can be both direct-initialized and copy-initialized from an rvalue.
And a copy constructor was able to initialize from an rvalue since the days of C++98. And it still works with the addition of move operations. That's why the trait is satisfied. Widget a; Widget b = std::move(a); is still valid, even in the absence of a move constructor, because the compiler provided copy constructor makes this possible.
The compiler not generating a move constructor was a design decision made to keep old code working when it made the move to C++11. Such code would have adhered to the rule of three, and so swapping the old copy for a compiler generated move was deemed risky. But old code could still initialize objects from rvalues, so the copy constructor retained its old function.
It is noteworthy that the trait may work as one expects in the future. A defaulted copy constructor being defined here is a deprecated feature:
[class.copy.ctor]
6 If the class definition does not explicitly declare a copy constructor, a non-explicit one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted; otherwise, it is defined as defaulted ([dcl.fct.def]). The latter case is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor ([depr.impldec]).
Related
Compiling following code gives "undefined reference to `A::~A()":
#include <cstdlib>
#include <memory>
template <typename T>
struct A {
A() {}
~A() {}
};
struct Aggregate {
using key_vector = A<char>;
using value_vector = A<int>;
value_vector vals;
key_vector keys;
};
int
main()
{
auto x = malloc(sizeof(Aggregate));
new (x) Aggregate{};
return 0;
}
the problem is present on clang 7.0 and 6.0 (possibly also some oolder versions). See: https://godbolt.org/z/GNPk3V
On newer clang versions and on gcc it works fine.
Is this expected or is it some kind of bug in clang?
This appears to be Bug 28280, fixed by https://reviews.llvm.org/D45898:
If an initializer in a braced-init-list is a C++ class that has a non-trivial destructor, mark the destructor as referenced. This fixes a crash in CodeGenFunction::destroyCXXObject that occurs when it tries to emit a call to the destructor on the stack unwinding path but the CXXRecordDecl of the class doesn't have a CXXDestructorDecl for the destructor.
This example does use a braced-init-list and emits the destructor call right before calling _Unwind_Resume. The destructor is not trivial. Changing the initialization to use () instead of {} makes the error go away because it's no longer initialized with a braced-init-list. The destructor call in my comment would presumably cause the destructor to be marked as referenced. Perhaps enabling optimization plays with the same things that make this appear only for non-trivial destructors.
I want to avoid inizializing an Eigen::CholmodDecomposition object each time I want to solve a sparse system. To do so, I have created a custom class. The sparse solver gets initialized with the class and then used whenever necessary, without requiring re-initialization. One thing I need to do later is a copy of such objects.
When I include both (1) Eigen::CholmodDecomposition in the class definition and (2) a copy operation, I get the errors below. If I remove either (either no copy, or no Eigen::CholmodDecomposition in the class) there is no error.
What am I breaking? Why is this not working? How do I make this work?
#include <RcppEigen.h>
using namespace std;
class TestClass{
public:
Eigen::CholmodDecomposition<Eigen::SparseMatrix<double> > solver;
Eigen::MatrixXd solve(const Eigen::SparseMatrix<double>&,
const Eigen::MatrixXd&);
TestClass(){};
};
Eigen::MatrixXd TestClass::solve(const Eigen::SparseMatrix<double>& A, const Eigen::MatrixXd& b){
solver.compute(A);
return solver.solve(b);
}
//[[Rcpp::export]]
Eigen::MatrixXd cholmodsolver(const Eigen::SparseMatrix<double>& A,
const Eigen::MatrixXd& b){
TestClass test;
TestClass test2 = test;
return test2.solve(A, b);
}
This gives the errors:
error: use of deleted function ‘TestClass::TestClass(const TestClass&)’
TestClass test2 = test;
^~~~
note: ‘TestClass::TestClass(const TestClass&)’ is implicitly deleted because the default definition would be ill-formed:
class TestClass{
^~~~~~~~~
error: use of deleted function ‘Eigen::CholmodDecomposition<Eigen::SparseMatrix<double, 0, int> >::CholmodDecomposition(const Eigen::CholmodDecomposition<Eigen::SparseMatrix<double, 0, int> >&)’
^~~~~~~~~~~~~~~~~~~~
The error is due to Eigen::CholmodDecomposition being a class that cannot be copied just like std::unique_ptr. This causes the copy constructor of TestClass, which has a member of type Eigen::CholmodDecomposition, to be implicitly defined as deleted.
This follows one of the rules of C++11:
C++11 § 12.8,p23:
A defaulted copy/move constructor for a class X is defined as deleted
(8.4.3) if X has:
...
a non-static data member of class type M (or array thereof) that
cannot be copied/moved because overload resolution (13.3), as applied
to M's corresponding constructor, results in an ambiguity or a
function that is deleted or inaccessible from the defaulted
constructor,
...
GCC isn't giving me an error on an example I've made where I was hoping it would:
class CannotBeCopied {
public:
CannotBeCopied(const CannotBeCopied&) = delete;
CannotBeCopied& operator=(const CannotBeCopied&) =delete;
CannotBeCopied() { }
~CannotBeCopied() { }
};
template<class T>
class FirstVector {
public:
FirstVector() {
size = 1;
data = new T[size];
}
~FirstVector() {
delete[] data;
}
FirstVector(const FirstVector& source) {
size = source.size;
data = new T[size];
for(int k=0;k!=size;k++) {
data[k] = source.data[k]; //<--I EXPECT AN ERROR HERE
}
}
private:
int size;
T* data;
};
This error doesn't happen when the copy constructor isn't use (that is, it does happen when the copy constructor is used).
Because of the template I cannot simply move the copy-ctor into a code file and have that fail when it compiles.
How can I get this to fail?
This is not SFINAE, it should not be able to instantiate the template. If the copy-ctor was itself a template method (say by putting:
template<class U=T>
on the line above, then it'd be SFINAE.
I am using GCC 4.8.1, -pedantic -Wall -Wextra of course, and -std=c++11
I was hoping to get this to fail with:
int main() {
FirstVector<CannotBeCopied> whatever;
}
I know that GCC is just being lazy and not doing work it doesn't need to, but I do not like that if I were to explicitly instantiate this template in a code file, I'd get an error. Is there a way to get the error I want?
If you don't actually create an instance of your template, the copy constructor doesn't need to be called - the template code will not even be created for CannotBeCopied, if you don't use it. Invoke the copy constructor and you will get the error:
FirstVector<CannotBeCopied> a;
FirstVector<CannotBeCopied> b = a;
Edit: You may also use explicit instantiation of the template with all it's members by adding
template class FirstVector<CannotBeCopied>;
(§14.7.2 of language specification)
Templates in C++ are only materialized when they are used.
Everything else would be too expensive.
As you may have heard, C++ templates are turing complete, so evaluating them can be is insanely expensive. IIRC there was an example somewhere of Fibonnaci<17>, which would have the compiler compute this number...
In particular this means the dead code will be eliminated, and the c++ compiler will only fail once you try to use the copy constructor.
It's not just a matter of GCC being lazy; it is affirmatively prohibited from doing what you want it to do by the standard. [temp.inst]/p1, 2, 11:
1 Unless a class template specialization has been explicitly
instantiated (14.7.2) or explicitly specialized (14.7.3), the class
template specialization is implicitly instantiated when the
specialization is referenced in a context that requires a
completely-defined object type or when the completeness of the class
type affects the semantics of the program. [...] The implicit instantiation of
a class template specialization causes the implicit instantiation of
the declarations, but not of the definitions, default arguments, or
exception-specifications of the class member functions [...]
2 Unless a member of a class template or a member template has been
explicitly instantiated or explicitly specialized, the specialization
of the member is implicitly instantiated when the specialization is
referenced in a context that requires the member definition to exist.
[...]
11 An implementation shall not implicitly instantiate a function
template, a variable template, a member template, a non-virtual member
function, a member class, or a static data member of a class template
that does not require instantiation.
This allows you to have, e.g., std::vectors of move-only types. Their copy constructors will not compile, but as long as you don't use them, a std::vector<std::unique_ptr<T>> is perfectly valid.
To force it to fail, you might use a static_assert inside FirstVector:
static_assert(std::is_copy_constructible<T>::value, "T must be copy constructible");
Note, however, that this only checks that a declaration of the copy constructor is accessible and not deleted, not that the body of the copy constructor will compile, which means that it will falsely report that std::vector<std::unique_ptr<T>> is copy constructible.
Suppose I have a public class and a private implementation class (e.g. PIMPL pattern), and I wish to wrap the private class with a template smart pointer class with a checked delete, as follows:
PublicClass.h
class PrivateClass;
// simple smart pointer with checked delete
template<class X> class demo_ptr
{
public:
demo_ptr (X* p) : the_p(p) { }
~demo_ptr () {
// from boost::checked_delete: don't allow compilation of incomplete type
typedef char type_must_be_complete[ sizeof(X)? 1: -1 ];
(void) sizeof(type_must_be_complete);
delete the_p;
}
private:
X* the_p;
};
// public-facing class that wishes to wrap some private implementation guts
class PublicClass
{
public:
PublicClass();
~PublicClass();
private:
demo_ptr<PrivateClass> pvt;
};
PublicClass.cpp
#include "PublicClass.h"
class PrivateClass
{
public:
// implementation stuff goes here...
PrivateClass() {}
};
//---------------------------------------------------------------------------
PublicClass::PublicClass() : pvt(new PrivateClass()) {}
PublicClass::~PublicClass() {}
main.cpp
#include "PublicClass.h"
int main()
{
PublicClass *test = new PublicClass();
delete test;
return 0;
}
This code compiles successfully on Visual C++ 2008, but fails to compile on an old version of C++ Builder. In particular, main.cpp does not compile because demo_ptr<PrivateClass>::~demo_ptr is being instantiated by main.cpp, and that destructor won't compile because it can't do sizeof on an incomplete type for PrivateClass. Clearly, it is not useful for the compiler to be instantiating ~demo_ptr in the consuming main.cpp, since it will never be able to generate a sensible implementation (seeing as how ~PrivateClass is not accessible). (PublicClass.cpp compiles fine on all tested compilers.)
My question is: what does the C++ standard say about implicit instantiation of a template class's member functions? Might it be one of the following? In particular, has this changed over the years?
If a template class is used, then all member functions of the class should be implicitly instantiated - whether used or not?
Or: template class functions should only be implicitly instantiated one at a time if actually used. If a particular template class function isn't used, then it shouldn't be implicitly instantiated - even if other template class functions are used and instantiated.
It seems clear that the second case is the case today because this same pattern is used with PIMPL and unique_ptr with its checked delete, but maybe that was not the case in the past? Was the first case acceptable compiler behavior in the past?
Or in other words, was the compiler buggy, or did it accurately follow the C++98 standard, and the standard changed over the years?
(Fun fact: if you remove the checked delete in C++ Builder, and have function inlining turned off, the project will happily compile. PublicClass.obj will contain a correct ~demo_ptr implementation, and main.obj will contain an incorrect ~demo_ptr implementation with undefined behavior. The function used will depend on the order in which these files are fed to the linker.)
UPDATE: This is due to a compiler bug, as noted by Andy Prowl, which is still not fixed in C++ Builder XE8. I've reported the bug to Embarcadero: bcc32 compiler causes undefined behavior when using std::auto_ptr with PIMPL idiom because template instantiation rules do not follow C++ spec
If a template class is used, then all member functions of the class should be implicitly instantiated - whether used or not?
No, this is definitely not the case. Per Paragraph 14.7.1/10 of the C++11 Standard (and Paragraph 14.7.1/9 of the C++03 Standard) very clearly specifies:
An implementation shall not implicitly instantiate a function template, a member template, a non-virtual
member function, a member class, or a static data member of a class template that does not require instantiation.
As for when instantiation is required, Paragraph 14.7.1/2 specifies:
Unless a member of a class template or a member template has been explicitly instantiated or explicitly
specialized, the specialization of the member is implicitly instantiated when the specialization is referenced
in a context that requires the member definition to exist; [...]
This is certainly not the case if a member function is never referenced.
Unfortunately, I can't provide an official reference on what the rules were before C++03, but to the best of my knowledge the same "lazy" instantiation mechanism was adopted in C++98.
unique_ptr is a funny beast.
Unlike auto_ptr, which called the destructor of the referenced object from the smart pointer destructor, unique_ptr::~unique_ptr merely invokes a deleter function which has been previously stored.
The deleter function is stored in the unique_ptr constructor, which is called for each and every PublicClass constructor. The user-defined constructor is defined in a context where PrivateClass::~PrivateClass is available, so that's ok. But what about other implicitly-generated PublicClass constructors, such as a move constructor? They're generated at the point of use; they also need to initialize the unique_ptr member, meaning they must supply a deleter. But without PrivateClass::~PrivateClass, they can't.
Wait, your question mentions unique_ptr, but your code isn't using it. Weird...
Even when the destructor is invoked from the smart pointer destructor, it can still be ODR-used from the containing class constructors. This is for exception-safety -- the constructor needs the capability to tear down a partially-constructed class, which includes destruction of members.
It looks like C++Builder may be generating a PublicClass copy or more constructor, even though your program doesn't use it. That doesn't fall afoul of the rule Andy mentioned, because PublicClass isn't a template. I think the compiler is entitled to generate a defaulted copy constructor for PublicClass when it processes the class definition, since you can't provide an out-of-class definition for a defaulted member. Respecting the rule of three for demo_ptr will preclude PublicClass having a copy constructor, and therefore may solve your problem.
I have a templated class that wraps a vector. I'm trying to store unique_ptrs in this class, and it works fine. However, when I mark the void add(const T& elem) function as virtual, my compiler (clang) tells me that I'm making a "call to implicitly-deleted copy constructor" for unique_ptr.
I understand that unique_ptrs can't be copied, so that's why I created the void add(T&& elem) function. I just don't know why marking the other add function as virtual causes the compiler error.
Thanks for your time.
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
template <typename T>
class ContainerWrapper {
private:
vector<T> vec;
public:
ContainerWrapper() : vec() {
}
//Marking this as virtual causes a compiler error
void add(const T& elem) {
vec.push_back(elem);
}
void add(T&& elem) {
vec.push_back(std::move(elem));
}
T removeLast() {
T last = std::move(vec.back());
vec.pop_back();
return last;
}
};
int main() {
ContainerWrapper<unique_ptr<string>> w;
w.add(unique_ptr<string>(new string("hello")));
unique_ptr<string> s = w.removeLast();
cout << *s << endl;
}
This is most likely due to ContainerWrapper being a template. With templates, the compiler most often won't even check member functions as long as you don't call them. However, marking it virtual forces the function to be present (you might also even get a link error).
You can possibly take a look at this post : When the virtual member functions of a template class instantiated?.
The problem here is that std::unique_ptr has its copy constructor marked as =delete. This means that the vec.push_back(elem) call inside the add(T const&) overloaded member function will not compile when being called with a std::unique_ptr. The compiler will realize this as soon as that member function is being instantiated.
The Standard has 2 relevant quotes here in 14.7.1 Implicit instantiation [temp.inst]:
6 If the overload resolution process can determine the correct
function to call without instantiating a class template definition, it
is unspecified whether that instantiation actually takes place.
10 [...] It is unspecified whether or not an implementation implicitly
instantiates a virtual member function of a class template if the
virtual member function would not otherwise be instantiated. [...]
Clause 6 states that -without the virtual keyword- the compiler is allowed but not required to instantiate both add(T const&) and add(T&&) in order to resolve which overload is the best match. Neither gcc 4.7.2 nor Clang 3.2 need the instantiation because they happen to deduce that rvalue references always are a better match for temporaries than lvalue references.
Clause 10 states that -even with the virtual keyword- the compiler is also allowed but not required to instantiate add(T const&) and add(T&&) in order to resolve which overload is the best match. Both gcc 4.7.2 and Clang 3.2 happen to the instantiate both member functions, even though they both could have deduced that the lvalue overload would never be a better match.
Note that if you make ContainerWrapper a regular class with a nested typedef unique_ptr<string> T;, then both gcc and Clang will generate errors with or without the virtual keyword because they have to generate code for both member functions. This will not be SFINAE'ed away because it the error does not happen during substitution of deduced arguments.
Conclusion: this is not a bug but a quality of implementation issue.