在c ++中,当类包含动态分配的数据时,显式定义复制构造函数operator =和destructor通常是合理的.但这些特殊方法的活动重叠.更具体地说,operator =通常首先进行一些破坏,然后它会复制类似于复制构造函数中的那个.
我的问题是如何在不重复相同代码行的情况下以最佳方式编写此代码,而无需处理器执行不必要的工作(如不必要的复制).
我通常最终得到两种帮助方法.一个用于施工,一个用于破坏.第一个是从复制构造函数和operator =调用的.第二个是析构函数和operator =使用的.
这是示例代码:
template <class T>
class MyClass
{
private:
// Data members
int count;
T* data; // Some of them are dynamicly allocated
void construct(const MyClass& myClass)
{
// Code which does deep copy
this->count = myClass.count;
data = new T[count];
try
{
for (int i = 0; i < count; i++)
data[i] = myClass.data[i];
}
catch (...)
{
delete[] data;
throw;
}
}
void destruct()
{
// Dealocate all dynamicly allocated data …Run Code Online (Sandbox Code Playgroud) c++ destructor copy-constructor code-sharing assignment-operator
我想要一个接口 A。这将允许类型 A 的对象生成类型 A 的其他对象。我需要类型 B 的相同行为。在我的应用程序中,所有 B 也是 A。所以我希望 B 成为源自 A。
这是我的尝试:
public interface A {
A method1();
}
public interface B : A {
overrride B method1();
void otherMethod();
}
Run Code Online (Sandbox Code Playgroud)
请注意,override 关键字此处无法编译。使项目编译的唯一方法是使接口 B 如下所示:
public interface B : A {
//A method1(); /* commented out because it is inherired */
void otherMethod();
}
Run Code Online (Sandbox Code Playgroud)
然而我想通过接口 B 承诺,这种类型的对象有方法生成 B 类型的其他对象。
接口 B 的实现可能如下所示:
class Foo : B {
B metod1();
}
Run Code Online (Sandbox Code Playgroud)
我想要从接口 BB metod1()实现B method1() …
我经常使用System.Diagnostics.Stopwatch来测量代码执行的时间.文档说它应该非常准确.我相信测量的时间只能与用于启动和停止秒表的时间不同.
我通过以下代码估计了这个错误有多大:
var sw = new Stopwatch();
sw.Start();
sw.Stop();
Run Code Online (Sandbox Code Playgroud)
它的测量值为:00:00:00.0000090.哇.错误低于10us.
经过多年的努力,我开始对秒表再次产生好奇心.真的那么精确吗?它是否测量挂钟时间?或者究竟是什么测量的定义在哪里?如果进程被IO操作阻止怎么办?它还是那么精确吗?
我再次做了小基准测试:
var sw = new Stopwatch();
var startTime = System.DateTime.Now;
sw.Start();
for (int i = 0; i < 1000; i++) {
Console.WriteLine(i);
Console.Error.WriteLine(i);
}
var endTime = System.DateTime.Now;
sw.Stop();
Console.Error.WriteLine(
@"The application was running {0}, but the stopwatch measured {1}.",
endTime - startTime,
sw.Elapsed
);
Run Code Online (Sandbox Code Playgroud)
当我正常启动应用程序时,输出是:
应用程序运行00:00:01.5740900,但秒表测量为00:00:01.5732109.差异几乎是1毫秒.
当我将应用程序的标准输出传递给在读取其输入之前等待一段时间的进程时,我得到以下结果:
应用程序运行00:04:51.2076561,但秒表测量为00:04:51.2012677.
差异超过6毫秒.
怎么了?秒表不准确吗?或者我只是误解了什么是未测量的?
编辑:我知道System.DateTime.Now具有较低的分辨率,但预计差异将以毫秒为单位.
c# ×2
.net ×1
c++ ×1
class ×1
code-sharing ×1
datetime ×1
destructor ×1
inheritance ×1
performance ×1
time ×1