本文介绍了如何通过编译错误找到在哪里使用C ++复制构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

简而言之:有什么方法可以修改类定义,以使其无论在何处使用都无法在复制构造函数的使用点编译?

In short: is there some way I can modify a class definition such that it fails to compile at the point of use of a copy constructor no matter where it's used?

我有一个非常大的项目,正在清理一些类定义.有一个我明确不想在其上使用复制构造函数的类(为便于讨论,我们忽略了为什么这样做),为了安全起见,我认为我只是将复制构造函数定义为私有而不是实际实现它...那样的话,如果我尝试在任何地方使用它,都会引发编译错误.瞧,它编译正常,但是我有一个链接器错误……未找到复制构造函数实现!大概这意味着它正在某处使用,但是我无法找到它在何处使用.顺便说一下,这是Visual Studio 2010.所以我的问题是,有什么方法可以修改类定义,使它在使用时无法编译?

I have a very large project and was cleaning up some class definitions. There's a class that I explicitly don't want to use copy constructors on (let's ignore why that is for the sake of this discussion), and in the interest of safety, I figured I'd just define the copy constructor as private and not actually implement it... that way it would throw a compile error if I tried to use it anywhere. Lo and behold, it compiles fine, but I have a linker error... the copy constructor implementation is not found! Presumably that means it's in use somewhere, but I'm unable to find where it's being used. This is Visual Studio 2010 by the way. So my question is, is there some way I can modify the class definition such that it fails to compile at the point of use?

class Sample {
private:
    // not implemented
    Sample( const Sample& rhs );
    Sample& operator=( const Sample& rhs );
public:
    // implemented
    Sample();
...
};

Sample *samp1 = new Sample;
Sample *samp2 = new Sample( *samp1 ); // <<-- inaccessible here!  this works

大概是因为我没有遇到编译错误,而是遇到了链接器错误,这意味着该类本身(或一个朋友)正在执行复制构造的创建(因为所有这些都可以访问私有的)构造函数),但我肯定找不到它!

Presumably since I'm not hitting a compile error, but am hitting the linker error, that it means the class itself (or a friend) is doing the copy-constructed create (since that's all that would have access to the private constructor), but I sure can't find it!

推荐答案

在C ++ 11中,您可以将定义更改为

in C++11 you can change the definition to

class Sample {
private:
    // not implemented
    Sample( const Sample& rhs ) = delete;
    Sample& operator=( const Sample& rhs ) = delete;
public:
    // implemented
    Sample();
...
};

在C ++ 11之前,通常是通过从声明了私有副本构造函数的类(例如 boost :: NonCopyAble (您可以简单地复制此类,只有几行).在这种情况下,您的班级(或任何朋友或孩子)也无法访问复制构造函数,它将生成编译时错误.

prior to C++11 this is usually done by inheritting from a class that declares a private copy constructor such as boost::NonCopyAble (you can simply copy this class, it's only a few lines). In this case your class (or any friends or children) also cannot access the copy constructor and it will generate a compile-time error.

这篇关于如何通过编译错误找到在哪里使用C ++复制构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:23