简体   繁体   English

C ++私有拷贝构造函数问题

[英]C++ private copy constructor issue

I am building a small C++ app and I was looking to make a private copy constructor for my reference holder. 我正在构建一个小型C ++应用程序,我正在寻找为我的参考持有者制作一个私有的复制构造函数。

When I use my class in my main, everything works, but when I try to test it with Google Test, I get an error stating that my copy constructor is private 当我在我的主要课程中使用我的课程时,一切正常,但是当我尝试使用Google Test测试它时,我收到一条错误,指出我的复制构造函数是私有的

TEST (Library, constructorParams) {
    Library lib = Library("my Library");
    ASSERT_EQ("my Library", lib.getNom());
}

Library.h (there is no definition for the copy constructor and the assignation operator in my .cpp) Library.h(我的.cpp中没有复制构造函数和赋值运算符的定义)

class Library {
public:
    ...
private:
    ...

    Library (const Library& obj);
    Library & operator=(const Library& obj);
};

Why am I getting an error for my private copy constructor (might it be a bad usage in my Tests?)? 为什么我的私有拷贝构造函数出错(可能在我的测试中使用不当?)?

Here 这里

Library lib = Library("my Library");

you are semantically performing a copy construction from a temporary object constructed on the RHS. 您在语义上从RHS上构造的临时对象执行复制构造。 Even of the compiler might optimize copies out, the copy constructor needs to be publicly accessible. 即使编译器可能会优化副本,复制构造函数也需要公开访问。

Try this instead: 试试这个:

Library lib("my Library");

See more on copy initialization . 详细了解复制初始化

Library lib = Library("my Library");

On this line you try to copy-construct an object of type Library , but this can't be done as its copy-constructor is private. 在这一行上,您尝试复制构造一个类型为Library的对象,但由于其copy-constructor是私有的,因此无法完成。 You should instead do this: 你应该这样做:

Library lib("my Library");

You are calling the copy constructor from this line of code 您正在从这行代码中调用复制构造函数

Library lib = Library("my Library");

And you have defined it as a private method of that class. 并且您已将其定义为该类的私有方法。

That operation is not related to a call to the assignment operator (which you mention in the question), this is more clear if you consider its equivalent: 该操作与对赋值运算符的调用无关(您在问题中提到),如果您考虑它的等价,则更清楚:

Library lib(Library("my Library"));  // Here the invocation of the copy 
                                     // constructor is more explicit

With the code in this format, it is also more clear that there's no need to first create the object in a temporary than call the copy constructor to create another instance of that object. 使用这种格式的代码,更清楚的是,不需要首先在临时中创建对象,而不是调用复制构造函数来创建该对象的另一个实例。

The correct way should be: 正确的方法应该是:

Library lib("my Library");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM